//
//  Utils.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/11/14.
//

import Foundation
import UIKit
import CoreData
import NotificationBannerSwift

let UserLogined = "UserLogined"
let SafetyToken = "SafetyToken"
let SafetyUserRole = "UserRole"
let SafetyUserInfo = "UserInfo"

let ScreenWidth = UIScreen.main.bounds.width
let ScreenHeight = UIScreen.main.bounds.height

let NotiInsp = NSNotification.Name(rawValue: "reload_insp")
let NotiRepair = NSNotification.Name(rawValue: "reload_repair")
let NotiSupervise = NSNotification.Name(rawValue: "reload_supervise")
let NotiAlarm = NSNotification.Name(rawValue: "reload_alarm")

let PageSize: Int = 10

class Utils {
    class func delay(second: TimeInterval = 1.0, complete: @escaping () -> Void) {
        DispatchQueue.main.asyncAfter(deadline: .now() + second) {
            complete()
        }
    }

    static var app: AppDelegate {
        let app = UIApplication.shared.delegate as! AppDelegate
        return app
    }

    static var context: NSManagedObjectContext {
        let context = app.persistentContainer.viewContext
        return context
    }

    class func exitApp(msg: String? = "未知错误") {
        let token = UserDefaults.standard.string(forKey: SafetyToken)
        if token == nil {
            return
        }
        exitApp()
        app.window?.showToast(witMsg: msg)
    }
    
    class func exitApp() {
        UserDefaults.standard.set(nil, forKey: SafetyToken)
        UserDefaults.standard.set(nil, forKey: SafetyUserRole)
        Utils.app.setupUI()
    }

    // 获取拼音首字母（大写字母）

    class func findFirstLetter(fromString aString: String) -> String {
        let mutableString = NSMutableString.init(string: aString)
        CFStringTransform(mutableString as CFMutableString, nil, kCFStringTransformToLatin, false)
        let pinyinString = mutableString.folding(options: String.CompareOptions.diacriticInsensitive, locale: NSLocale.current)
        let strPinYin = polyphoneStringHandle(nameString: aString, pinyinString: pinyinString).uppercased()
        let firstString = "\(strPinYin.prefix(1))"
        let regexA = "^[A-Z]$"
        let predA = NSPredicate.init(format: "SELF MATCHES %@", regexA)
        return predA.evaluate(with: firstString) ? firstString : "#"
    }

    // 多音字处理

    class func polyphoneStringHandle(nameString: String, pinyinString: String) -> String {
        if nameString.hasPrefix("长") {
            return "chang"
        }
        if nameString.hasPrefix("沈") {
            return "shen"
        }
        if nameString.hasPrefix("厦") {
            return "xia"
        }
        if nameString.hasPrefix("地") {
            return "di"
        }
        if nameString.hasPrefix("重") {
            return "chong"
        }
        return pinyinString
    }
    
    // 验证手机号
    static func isPhoneNumber(phone: String) -> Bool {
        let phoneString = "^((1[3-9][0-9]))\\d{8}$"
        let phonePredicate = NSPredicate(format:"SELF MATCHES %@", phoneString)
        return phonePredicate.evaluate(with: phone)
    }
    
    static func showBanner(_ model: NoticeOwnerInfoModal) {
        let banner = NotificationBanner(title: model.noticeTitle, subtitle: model.noticeContent?.html2String, style: .info)
        banner.subtitleLabel?.labelize = true
        banner.show()
        banner.onTap = { () -> () in
           // 模块类型代码 1.报警通知、2履职管理、3维保服务、4智慧内保、5一键报修、6台账管理、7检查监督、8智慧保安
            let topNavi = (Utils.app.window?.rootViewController as? UITabBarController)?.selectedViewController as? UINavigationController
            
            if model.noticeType == "1" || model.noticeType == "2" || model.noticeType == "3" {
                topNavi?.pushViewController(NotiDetailVC(id: model.noticeId!), animated: true)
                banner.dismiss(forced: true)
                return
            }
            
            let deptId = BSUser.currentUser.deptId
            let deptName = BSUser.currentUser.deptName
            switch model.mklxdm {
            case "1": // 1.报警通知
                topNavi?.pushViewController(AlarmHomeVC(withDeptId: deptId, deptName: deptName), animated: true)
                break
            case "2": // 履职管理
                topNavi?.pushViewController(TaskHomeVC(withDeptId: deptId, deptName: deptName), animated: true)
                break
            case "3": // 维保服务
                topNavi?.pushViewController(InspListVC(withDeptId: deptId, deptName: deptName, wbtype: model.mkywid), animated: true)
                break
            case "5": // 一键报修
                topNavi?.pushViewController(RepairHomeVC(withDeptId: deptId, deptName: deptName, isSel: true), animated: true)
                break
            case "6": // 台账管理
                topNavi?.pushViewController(ElecLedgerHomeVC(withDeptId: deptId, deptName: deptName), animated: true)
                break
            case "7": // 检查监督
                topNavi?.pushViewController(SuperviseHomeVC(withDeptId: deptId, deptName: deptName, isSel: true), animated: true)
                break
            case "8": // 智慧保安
//                topNavi?.pushViewController(SecurityStatisticsTopVC(withDeptId: deptId, deptName: deptName), animated: true)
                Utils.app.window?.rootViewController = UINavigationController(rootViewController: SecurityHomeVC())
                break
            default: // 4.智慧内保
                break
            }
            
            banner.dismiss(forced: true)
        }
    }
}
